package com.qf.automation.file.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码的工具类
 */
public class QRCodeUtil {
    public static BufferedImage qrEncode(String content,int onColor,int offColor){
        return qrEncode(content, onColor, offColor, 200, 200);
    }
    public static BufferedImage qrEncode(String content,int onColor){
        return qrEncode(content, onColor,0xffffffff);
    }
    public static BufferedImage qrEncode(String content){
        return qrEncode(content, 0xff000000, 0xffffffff);
    }


    /**
     *生成二维码的方法
     * @param content  二维码携带的信息
     * @param onColor  二维码的颜色1
     * @param offColor  二维码的颜色2
     * @param w     二维码的宽度
     * @param h       二维码的高度
     * @return  返回二维码图片
     */
    public static BufferedImage qrEncode(String content,int onColor,int offColor,int w,int h){
        //接收宽高
        int width=w;
        int height=h;
        //实例二维码的属性元素
        //人的属性  年龄，肤色，发色
        Map<EncodeHintType,Object> hints=new HashMap<>();
        //二位的属性：内容编码
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        //二维码的属性：纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //设置二维码边界的空白的宽度
        hints.put(EncodeHintType.MARGIN,1);
        //绘制二维码的为信息的对象
        BitMatrix bitMatrix=null;
        //用于保存二维码结果的对象
        BufferedImage bufferedImage=null;
        //要写如二维码的对象
        try {
            bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height);
            //写如到具体的二维码中的配置信息
            MatrixToImageConfig config=new MatrixToImageConfig(onColor,offColor);
            //生成二维码图片
            bufferedImage= MatrixToImageWriter.toBufferedImage(bitMatrix,config);
            File file=new File("E://TEST/baidu.png");
            file.createNewFile();
            ImageIO.write(bufferedImage,"png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bufferedImage;
    }

    public static void main(String[] args) {
        BufferedImage bufferedImage = qrEncode("http://www.baidu.com", 0xff000000, 0xfffffff, 200, 200);
        File file=new File("E://TEST/baidu.png");
        try {
            file.createNewFile();
            ImageIO.write(bufferedImage,"png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

